package com.acme.service;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeSet;

import com.acme.domain.Operationtype;
import com.acme.domain.Order;
import com.acme.domain.Orderstatus;

public class MatchService {
	
	public static boolean match(Order o, TreeSet<Order> orders){
		Iterator<Order> iter;
		boolean matched = false;
		if (o.getOpperationType() == Operationtype.SELL){
			iter = orders.descendingIterator();
		} else {
			iter = orders.iterator();
		}
		
		try {
			while(iter.hasNext()){
				Order currentOrder = iter.next();
				if (currentOrder.getOpperationType() == o.getOpperationType()){
					break;
				} else {
					if (comparePrice(currentOrder,o)) {
						if ( currentOrder.getNumberOfShares() <= o.getNumberOfShares()){
							iter.remove();
							proceedMatch(o, currentOrder);
						} else {	
							proceedMatch(currentOrder,o);
							matched = true;
						}
					}
				}
			}
		} catch (IOException ex){
			ex.printStackTrace();
		}
		return matched;
	}

	private static void proceedMatch(Order o, Order currentOrder)
			throws IOException {
		currentOrder.setStatus(Orderstatus.EXECUTED);
		o.setStatus(Orderstatus.PARTIAL);
		o.getNShares(
			o.getNumberOfShares() - currentOrder.getNumberOfShares()
		);
	}
	
	private static boolean comparePrice(Order orderInMap, Order newOrder){
		int result = new Float(orderInMap.getPrice()).compareTo(new Float(newOrder.getPrice()));
		if (orderInMap.getOpperationType() == Operationtype.BUY){
			result = -result;
		}
		
		if (result<=0){
			return true;
		} else {
			return false;
		}
	}
}